package com.zking.forward.shopping;

import com.zking.dao.ProductDao;
import com.zking.dao.ShopCarDao;
import com.zking.entity.Product;
import com.zking.entity.User;
import com.zking.util.RedirectMsg;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

@WebServlet("/updateShopCar")
public class UpdateShopCar extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("UpdateShopCar===进来");

        String sid = request.getParameter("id");
        String snum = request.getParameter("num");

        sid = URLDecoder.decode(sid,"utf-8");
        snum = URLDecoder.decode(snum,"utf-8");
        int id = Integer.parseInt(sid);//商品的编号
        int num = Integer.parseInt(snum);//商品的数量

        System.out.println("UpdateShopCar:"+id+"==="+num);

        //1.拿到购物车
        PrintWriter out = response.getWriter();

        //完善更新购物车表中商品的数量
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        // 对没登陆情况的处理
        if(user==null){
            request.setAttribute("msg", RedirectMsg.notLogin);
            request.setAttribute("pageName", RedirectMsg.loginPageName);
            request.setAttribute("url", RedirectMsg.loginUrl);
            request.getRequestDispatcher("redirect.jsp").forward(request, response);
            return;
        }
        String eu_user_id = user.getEu_user_id();

        boolean flag = num==1?true:false;
        Integer count = ShopCarDao.updateShopCar(eu_user_id, id, flag);

        Product product = ProductDao.selectProductById(id);
        if(product!=null){
            out.print(count+"-"+count*product.getEp_price());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
